import db.DatabaseConnection;
import strategy.DefaultValidationStrategy;
import strategy.TransactionProcessor;
import subject.AccountManager;
import subject.TransactionLogger;
import trans.ExpenseTransaction;
import trans.IncomeTransaction;
import trans.Transaction;
import trans.TransactionFactory;

import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        AccountManager accountManager = new AccountManager();
        TransactionProcessor transactionProcessor = new TransactionProcessor();
        TransactionLogger logger = new TransactionLogger();

        // 注册观察者
        accountManager.registerObserver(logger);


        // 设置默认验证策略
        transactionProcessor.setValidationStrategy(new DefaultValidationStrategy());

        while (true) {
            System.out.println("请选择操作：");
            System.out.println("1. 添加记账");
            System.out.println("2. 删除记账");
            System.out.println("3. 查询记账");
            System.out.println("4. 更新记账");
            System.out.println("5. 退出");

            String choice = scanner.nextLine();
            switch (choice) {
                case "1":
                    addTransaction(scanner, accountManager, transactionProcessor);
                    break;
                case "2":
                    deleteTransaction(scanner, accountManager);
                    break;
                case "3":
                    listAllTransactions( accountManager);
                    break;
                case "4":
                    updateTransaction(scanner, accountManager, transactionProcessor);
                    break;
                case "5":
                    System.out.println("退出程序。");
                    scanner.close();
                    DatabaseConnection.getInstance().closeConnection();
                    return;
                default:
                    System.out.println("无效的选择，请重新输入。");
            }
        }
    }

    private static void addTransaction(Scanner scanner, AccountManager accountManager, TransactionProcessor transactionProcessor) {
        System.out.println("请输入记账类型（收入/支出），描述和金额，用/分隔：");
        String input = scanner.nextLine();
        String[] parts = input.split("/");
        if (parts.length != 3) {
            System.out.println("输入格式错误，请重新输入。");
            return;
        }

        String type = parts[0];
        String description = parts[1];
        double amount = Double.parseDouble(parts[2]);

        Transaction transaction = TransactionFactory.createTransaction(type, description, amount);
        transactionProcessor.processTransaction(transaction);
        if (transaction instanceof ExpenseTransaction || transaction instanceof IncomeTransaction) {
            accountManager.addTransaction(transaction);
        }
    }

    private static void deleteTransaction(Scanner scanner, AccountManager accountManager) {
        System.out.println("请输入要删除的记账ID：");
        int id = Integer.parseInt(scanner.nextLine());
        accountManager.deleteTransaction(id);
    }

    private static void listAllTransactions(AccountManager accountManager) {
        List<Transaction> transactions = accountManager.getAllTransactionsFromDatabase();
        if (transactions.isEmpty()) {
            System.out.println("没有记账记录。");
        } else {
            System.out.println("所有记账记录：");
            for (Transaction transaction : transactions) {
                System.out.println(transaction);
            }
        }
    }

    private static void updateTransaction(Scanner scanner, AccountManager accountManager, TransactionProcessor transactionProcessor) {
        listAllTransactions(accountManager); // 先列出所有记账
        System.out.println("请输入要更新的记账ID：");
        int id = Integer.parseInt(scanner.nextLine());
        Transaction existingTransaction = accountManager.getTransactionById(id);
        if (existingTransaction == null) {
            System.out.println("未找到该记账。");
            return;
        }

        System.out.println("请输入新的记账类型（收入/支出），描述和金额，用/分隔：");
        String input = scanner.nextLine();
        String[] parts = input.split("/");
        if (parts.length != 3) {
            System.out.println("输入格式错误，请重新输入。");
            return;
        }

        String type = parts[0];
        String description = parts[1];
        double amount = Double.parseDouble(parts[2]);

        Transaction newTransaction = TransactionFactory.createTransaction(type, description, amount);
        newTransaction.setId(id); // 设置相同的ID
        transactionProcessor.processTransaction(newTransaction);
//        accountManager.updateTransaction(newTransaction);
        accountManager.deleteTransaction(id);
        accountManager.addTransaction(newTransaction);
    }
}